import type { JSONSchema7, JSONSchema7Definition } from "json-schema";

/** 定义校验规则 */
interface DefineSchemaOption {
	/** 请求体校验 */
	body?: JSONSchema7;
	/** 返回数据校验 */
	response?: { [key: string]: JSONSchema7Definition };
}

/** 定义校验规则 */
interface DefineSchemaResponse {
	/** 请求体校验 */
	body?: JSONSchema7;
	/** 返回数据校验 */
	response: {
		200: JSONSchema7;
	};
}

/**
 * 定义接口校验规则
 * @param option 校验规则
 * @returns 接口请求和返回的校验规则
 */
export function defineSchema(option: DefineSchemaOption) {
	const baseResProperties: { [key: string]: JSONSchema7Definition } = {
		code: { type: "integer" },
		message: { type: "string" },
	};
	if (option.response) {
		baseResProperties.data = option.response;
	}
	const schema: DefineSchemaResponse = {
		response: {
			200: {
				type: "object",
				required: ["code", "message"],
				properties: baseResProperties,
			},
		},
	};
	if (option.body) {
		schema.body = option.body;
	}
	return schema;
}

export const pingSchema = defineSchema({});

export const loginSchema = defineSchema({
	body: {
		type: "object",
		required: ["username", "password"],
		properties: {
			username: {
				type: "string",
				minLength: 3,
				maxLength: 20,
			},
			password: {
				type: "string",
				minLength: 6,
				maxLength: 20,
			},
		},
	},
	response: {
		token: { type: "string" },
	},
});
